package com.dgy.roomEval.service.impl;

import com.dgy.roomEval.domain.XsGyFjhBh;
import com.dgy.roomEval.mapper.XsGyFjhBhMapper;
import com.dgy.roomEval.pojo.vo.RoomTreeVO;
import com.dgy.roomEval.service.IXsGyFjhBhService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 学生公寓房间相关Service业务处理
 *
 * @author ccc
 * @date 2025-02-15
 */
@Service
public class XsGyFjhBhServiceImpl implements IXsGyFjhBhService
{
    @Autowired
    private XsGyFjhBhMapper xsGyFjhBhMapper;


    @Override
    public List<RoomTreeVO> getRoomTree() {
        // 获取符合条件的房间列表
        List<XsGyFjhBh> roomList = xsGyFjhBhMapper.selectRoomList();
        // 组装成树
        return listToTree(roomList);
    }

    /**
     *  list转为tree
     */
    protected List<RoomTreeVO> listToTree(List<XsGyFjhBh> roomList) {
        // 找出所有楼栋
        Map<String, RoomTreeVO> buildingMap = new HashMap<>();
        Map<String, RoomTreeVO> floorMap = new HashMap<>();

        // 构建楼栋和楼层的映射
        for (XsGyFjhBh room : roomList) {
            String buildingId = room.getLd();
            String buildingName = room.getLdT();
            String floorId = room.getLc();
            String floorName = room.getLcT();
            String roomId = room.getFjhBh();
            String roomName = room.getFj();

            // 处理楼栋
            buildingMap.computeIfAbsent(buildingId, k -> new RoomTreeVO(buildingId, buildingName));

            // 处理楼层
            RoomTreeVO floorNode = floorMap.computeIfAbsent(floorId, k -> {
                RoomTreeVO newFloor = new RoomTreeVO(floorId, floorName);
                buildingMap.get(buildingId).getChildren().add(newFloor);
                return newFloor;
            });

            // 处理房间
            RoomTreeVO roomNode = new RoomTreeVO(roomId, roomName);
            floorNode.getChildren().add(roomNode);
        }

        return new ArrayList<>(buildingMap.values());
    }
}
